package com.bigteddy.BankMark;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class FibonacciActivity extends Activity {
	TextView prot;
	TextProgressBar prog;
	Button but;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fibonacci);

		but = (Button) findViewById(R.id.f_calc_button);
		prot = (TextView) findViewById(R.id.editText2);
		prog = (TextProgressBar) findViewById(R.id.progressBar1);
		prog.setTextSize(20);
		but.setOnClickListener(new AdapterView.OnClickListener() {
			@Override
			public void onClick(View v) {
				but.setEnabled(false);

				prot.setText("");
				EditText iterations = (EditText) findViewById(R.id.editText1);
				prog.setMax(Integer.parseInt(iterations.getText().toString()));
				prog.setText("Calculating...");

				new CalcFibTask().execute(iterations.getText().toString());
			}
		});
	}

	class CalcFibTask extends AsyncTask<String, Integer, String> {

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
			prog.setProgress(values[0]);
			prog.setText("Calculated " + values[0] + ". Iteration");
		}

		@Override
		protected void onPreExecute() {
			System.gc();
		}

		@Override
		protected void onPostExecute(String result) {
			prot.setText(result);
			prog.setText("Done!");
			but.setEnabled(true);
		}

		@Override
		protected String doInBackground(String... params) {
			StringBuilder sb = new StringBuilder();
			sb.append("Fibonacci number:\n");
			final int N = Integer.parseInt(params[0]);
			long then = SystemClock.elapsedRealtime();
			for (int i = 1; i <= N; i++) {
				sb.append(i + " : " + fib(i) + ";\n");
				publishProgress(i);
			}
			long elapsed = SystemClock.elapsedRealtime() - then;
			String old = sb.toString();
			sb.delete(0, sb.length());
			sb.append("The actual data you want:\n");
			sb.append("Elapsed Time: " + elapsed + "ms!" + "\n\n");
			sb.append(old);
			return sb.toString();
		}

		private long fib(int n) {
			if (n <= 1)
				return n;
			else
				return fib(n - 1) + fib(n - 2);
		}
	}

}
